const Koa = require('koa');
// const koaBody = require('koa-body')
const fs = require('fs');
// 注意require('koa-router')返回的是函数:
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
//渲染模版引擎
const engine =require('./middleware/templateEngine');

//引入模型
 
/* //链接数据库
const model = require('./model');
const Sequelize = require('sequelize');//连接数据库驱动
const config = require('./config'); //数据库配置 */

const controller = require('./controller'); //扫描路由 

    /*
//封装到db文件下
var sequelize = new Sequelize(config.database, config.username, config.password, {
    host: config.host,
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 0,
        idle: 30000
    }
});
 //封装到models、model下自动读取模型
var Pet=sequelize.define('pet',{
		id: {
			type: Sequelize.STRING(50),
			primaryKey: true
		},
		name: Sequelize.STRING(100),
		gender: Sequelize.BOOLEAN,
		birth: Sequelize.STRING(10),
		createdAt: Sequelize.BIGINT,
		updatedAt: Sequelize.BIGINT,
		version: Sequelize.BIGINT
	}, {
		timestamps: false //关闭Sequelize的自动添加timestamp的功能,总是自作聪明地加上所谓“自动化”的功能，但是会让人感到完全摸不着头脑。
	}); 
*/	   
  /* let Pet=model.user;    
	 var now = Date.now();
	Pet.create({
		id: 'g-' + now,
		name: 'Gaffey',
		gender: false,
		birth: '2007-07-07',
		createdAt: now,
		updatedAt: now,
		version: 0
	}).then(function (p) {
		console.log('创建插入语句' + JSON.stringify(p));
	}).catch(function (err) {
		console.log('failed: ' + err);
	});	
	Pet.findAll({
	    where: { name: 'Gaffey'}
	}).then(res=>{
		console.log('查询名字叫Gaffey的所有人: ' + JSON.stringify(res)); 
		// 更新
		update(res)
	}).catch(err=>{
		console.log('failed: ' + err);
	}) 
	//更新
	let update=args=>{
		args.forEach(item=>{
			// if(item.id=='1'){
				item.gender = true;
				item.updatedAt = Date.now();
				item.version ++;
				item.save();
			// }
		})
	}
	 //对查询出的实体进行修改
	Pet.queryFromSomewhere({id:1}).then(res=>{
		res.gender = true;
		res.updatedAt = Date.now();
		res.version ++;
		res.save();
	}) 
	
	// //删除查询出的实例
	Pet.queryFromSomewhere({id:1}).then(res=>{
		res.gender = true;
		res.updatedAt = Date.now();
		res.version ++;
		res.destroy();
	}) */
	
const app = new Koa();  
//解析post请求的body属性 中间件
app.use(bodyParser()); 

//默认中间件
app.use(async (ctx, next) => { 
	 // if (ctx.request.path === '/test'){} 
	 var start = new Date().getTime(), execTime; 
	 ctx.center="我是中间件添加的属性值";
	 await next();//记录执行时间
	 execTime = new Date().getTime() - start;
	 ctx.response.set('X-Response-Time', `${execTime}ms`); 
});  
//给cxt添加render()方法渲染指定模板引擎的中间件
const isProduction = process.env.NODE_ENV === 'production';
app.use(engine.templating('views', {
	noCache: !isProduction,//开发模式禁止缓存，否则修改代码刷新浏览器看不见效果
	watch: !isProduction
})); 

//添加静态资源图片样式网页模板中间件过滤static和public路径
let staticFiles = require('./middleware/static-files'); 
app.use(staticFiles('/public/', __dirname + '/public')); 

//统一处理cxt响应格式
let interceptor= require('./middleware/Interceptor'); 
app.use(interceptor.restify());//设置统一相应;

app.use(interceptor.checkToken());//拦截token;
 
/* //手动添加路由配置
router.get('/hello/:name', async (ctx, next) => {
    var name = ctx.params.name;
    ctx.response.body = `<h1>Hello, ${name}!</h1>`;
}); 
router.get('/', async (ctx, next) => {
    ctx.response.body = '<h1>Index</h1>';
}); 
// 先导入fs模块，然后用readdirSync列出文件
// 这里可以用sync是因为启动时只运行一次，不存在性能问题: 
  function addControllers(router) {
    var files = fs.readdirSync(__dirname + '/controllers');  
    var js_files = files.filter((f) => {
        return f.endsWith('.js');//返回所有以js结尾的文件名
    }); 
    for (var f of js_files) {  
        let mapping = require(__dirname + '/controllers/' + f);  
		for (var url in mapping) {
		    if (url.startsWith('GET ')) {
		        var path = url.substring(4);
		        router.get(path, mapping[url]); 
		    } else if (url.startsWith('POST ')) {
		        var path = url.substring(5);
		        router.post(path, mapping[url]); 
		    } else {
		        console.error(`无效路径: ${url}`);
		    }
		}
    }
}   
//自动方式读取路由文件进行路由配置
addControllers(router); 
//加载路由 
app.use(router.routes());  
 */

//加载controllers下的所有路由
// app.use(koaBody({
//   multipart: true,
//   strict:false,//设为false
//   formidable: {
//       maxFileSize: 200 * 1024 * 1024
//   }
// }))


 app.use(controller()); 
 // console.log(controller()); 

app.listen(3000); 
console.log('app启动成功监听端口号：3000');